package com.xzl.xep.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.xzl.xep.common.utils.DateUtil;
import com.xzl.xep.pojo.Product;
import com.xzl.xep.service.ProductService;


@Service
public class ProductServiceImpl extends BaseServiceImpl implements ProductService {

	@Override
	public List<Product> getProducts(Long companyId) {
		
		StringBuffer sb = new StringBuffer();
		
		sb.append("from Product c where c.status != -1");
		if(companyId != 0)
			sb.append(" and c.companyId = ").append(companyId);
		sb.append(" order by modifyTime desc");
		
		return dao.selectByHql(sb.toString());
	}

	@Override
	public Product addProduct(Product product) {
		
		product.setCreateTime(DateUtil.getCurrentDate());
		product.setModifyTime(DateUtil.getCurrentDate() );
		product.setStatus(1);
		product.setSaleAmountsLast(0d);
		product.setSaleAmountsTotal(0d);
		product.setSaleCountsLast(0);
		product.setSaleCountsTotal(0);
		
		return dao.saveObject(product);
	}

	@Override
	public boolean checkCustomerExists(Product product) {
		
		StringBuffer sb = new StringBuffer();
		sb.append("select count(*) from Product c where companyId = ").append(product.getCompanyId());
		sb.append(" and ( code = '").append(product.getCode()).append("'");
		sb.append(" or name = '").append(product.getName()).append("'");
		sb.append(" ) "); 
		
		if(dao.selectIntByHql(sb.toString()) >0 )
			return false;
		
		return true;
	}

	@Override
	public List<Product> queryCode(Long companyId, String code) {
		
		StringBuffer sb = new StringBuffer();
		
		sb.append("from Product c where 1=1 ");
		if(companyId != 0)
			sb.append(" and c.companyId = ").append(companyId);
		sb.append(" and c.code like '%").append(code).append("%' ");
		sb.append(" order by code asc ");
		
		return dao.selectByHql(sb.toString(), 0, 10);
	}

}
